package flex.cc.vehicle_svr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import flex.cc.PublicUtil;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.util.EncryptionDecryption;
import flex.cc.vehicle_svr.service.InputService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 上游下单接口
 */
@RestController
@RequestMapping(value = "/vehicleSvr")
public class InputController extends BaseController {

    @Autowired
    private InputService inputService;

    /**
     * 上游下单接口
     */
    @SuppressWarnings("static-access")
	@ResponseBody
    @RequestMapping("/inputOrder")
    public String inputOrder(HttpServletRequest request) throws Exception {
        // 进入接口时间
        long startTime = System.currentTimeMillis();
        logger.info("vehicleSvr/inputOrder 进入接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));

        Boolean flag = true;
        String responseMsg = "成功";
        EncryptionDecryption des = new EncryptionDecryption();
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            requestJson = URLDecoder.decode(requestJson, "UTF-8");
            if (requestJson != null && !"".equals(requestJson)) {
                // 调用业务处理 =============================
            	logger.info("vehicleSvr/inputOrder requestJson:" + requestJson);
            	requestJson = des.decrypt(requestJson, "UTF-8");
            	logger.info("下单报文解密后=" + requestJson);
                JSONObject jsonObject = JSONObject.parseObject(requestJson);
                JSONObject requestHeader = (JSONObject)jsonObject.get("requestHeader");
                JSONObject requestBody = (JSONObject)jsonObject.get("requestBody");
                Map requestHeaderMap = requestHeader.toJavaObject(Map.class);
                String requestCode = PublicUtil.isNotEmpty(requestHeaderMap.get("requestCode")) ? requestHeaderMap.get("requestCode").toString() : null;
                //TODO 车服二期，用clientId区分渠道来源；阳光-SUN_HYJY_RESCUE
                String clientId = PublicUtil.isNotEmpty(requestHeaderMap.get("clientId")) ? requestHeaderMap.get("clientId").toString() : null;
                
                if ("createRescue".equals(requestCode)) {
                    Map<String, Object> requestBodyMap = requestBody.toJavaObject(Map.class);
                    String result = inputService.inputOrder_V3(requestBodyMap, clientId); //四期-护理需求，增加车牌号重复下单判断
//                    String result = inputService.inputOrder_V2(requestBodyMap, clientId); //二期使用
//                    String result = inputService.inputOrder(requestBodyMap);
                    if (result != null) {
                        JSONObject resultObject = JSONObject.parseObject(result);

                        System.out.println("resultObject: " + result);
                        Integer resultCode = Integer.valueOf(resultObject.get("resultCode").toString());
                        String message = PublicUtil.isNotEmpty(resultObject.get("message")) ? resultObject.get("message").toString() : null;
                        if (resultCode == 0) {
                            flag = true;
                            responseMsg = "下单成功";
                        } else if(resultCode == 3){
                        	flag = false;
                            responseMsg = message;
                        }else {
                            flag = false;
                            responseMsg = message;
                        }
                    } else {
                        flag = false;
                        responseMsg = "下单接口请求异常";
                    }
                }else{
                	flag = false;
                    responseMsg = "下单失败:resultCode传参有误";
                }

            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("vehicleSvr/inputOrder 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("vehicleSvr/inputOrder 数据接收异常:" + e.getMessage());
        }
        // 生成响应报文
        String responseJson = "";
        Map<String, String> response = new HashMap<String, String>();
        if(flag){
            response.put("responseCode", "00");
        } else {
            response.put("responseCode", "01");
        }
        response.put("responseMsg", responseMsg);
        responseJson = JSON.toJSONString(response);
        logger.info("vehicleSvr/inputOrder responseJson:" + responseJson);

        // 离开接口时间
        long endTime = System.currentTimeMillis();
        logger.info("vehicleSvr/inputOrder 离开接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + ";处理时长:" + (endTime - startTime));

        return des.encrypt(responseJson);
    }
}
